import axios from "axios";
import store from "@/store";
import auth from "@/util/auth";


axios.defaults.headers.common["X-Requested-With"] = "XMLHttpRequest";
const http = axios.create();

http.interceptors.request.use(
  (config) => {

    if (config.requireToken){//前后端分离架构下，需要将令牌存于请求头部

      if (store.state.token) {
        config.headers["Authorization"] = `Bearer ${store.state.token}`;
      }
    }

    config.headers["Content-Type"] =
      config.headers["Content-Type"] || "application/json";
    config.headers["Accept"] = "application/json, text/plain, */*";
    if (config.showProcessing) store.commit("loading", true);

    return config;
  },
  (error) => {
    let config = error.config;
    if (config.showProcessing) store.commit("loading", false);
    return Promise.reject(error);
  }
);

http.interceptors.response.use(
  (response) => {
    let config = response.config;
    if (config.showProcessing) store.commit("loading", false);
    if (
      config.responseType == "blob" ||
      config.responseType === "arraybuffer"
    ) {
      //blob 下载

      const type = response.data.type;

      if (type.contains("application/json")) {
        let reader = new FileReader();
        reader.onload = (e) => {
          if (e.target.readyState === 2) {
            let data = JSON.parse(e.target.result);
            if (config.autoMsg && data && data.message) info(data.message);
            return data;
          }
        };
        reader.readAsText(response.data);
      } else {
        if (config.handleBlob) {
          return response;
        } else {
          let url = window.URL.createObjectURL(response.data);
          let contentDisposition = response.headers["content-disposition"];
          let patt = new RegExp("filename=([^;]+\\.[^\\.;]+);*");
          let result = patt.exec(contentDisposition);
          let filename = result[1].urlDecode().trim('\n').trim('\r').trim('\t').trim();
          let link = document.createElement("a");
          link.href = url;
          link.download = filename;
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
          window.URL.revokeObjectURL(url);
        }
      }
    } else {
      if (config.nowrap) {
        return response;
      } else {
        let data = response.data;
        if (data.success){
          if (config.autoMsg && data && data.message) success(data.message);
        }
        else{
          if (data.code == "40101"){
            if (config.autoMsg){
              info(data.message, ()=>{
                auth.gotoSSO();
              });
            }
            else{
              auth.gotoSSO();
            }
          }
          else{
            if (config.autoMsg && data && data.message) warning(data.message);
          }
        }

        return data;
      }
    }
  },
  (error) => {
    let config = error.config;
    if (config.showProcessing) store.commit("loading", false);
    let response = error.response;
    if (response) {
      let data = response.data;
      if (data && data.message) {
        fail(data.message);
      }
      return Promise.reject(config.nowrap ? response : data);
    } else {
      let msg = error.message;
      if (msg) {
        fail(msg);
      }
      return Promise.reject(error);
    }
  }
);

export default http;
